import { UserTypes } from "../types/userTypes";
import { UserActions } from "@actions/userActions";
import { User } from "user";
//用户登录凭据的类型
export interface Credentials{
    token:string
    refresh_token: string;
} 

//管理员信息的类型
export interface UserInfo{
  result:Partial<User>
  status: 'idle' | 'pending' | 'success' | 'error',
  error:string |null
}


//当前 Reducer 函数管理的状态的类型
export interface UserState{
    // 用户登录凭据
    credentials:Partial<Credentials>
    //管理员信息
    user:UserInfo
}

const initialState:UserState ={
  credentials:{
    token:"",
    refresh_token:''
  },
  user:{
    result:{},
    status:'idle',
    error:null
  }
}


export default function userReducer( state:UserState=initialState,aciton:UserActions.Actions):UserState{
    switch(aciton.type){
        case UserTypes.REQUEST_USER_INFO:
          return{
            ...state,
            user:{
              result:{},
              status:'pending',
              error:null
            }
          }
        
        case UserTypes.REQUEST_USER_INFO_SUCCESS:
          return{
            ...state,
            user:{
              result:aciton.payload,
              status:'success',
              error:null
            }
          }
        
        case UserTypes.REQUEST_USER_INFO_ERROR:
          return{
            ...state,
            user:{
              result:{},
              status:'error',
              error:aciton.error
            }
          }

        case UserTypes.SAVE_CREDENTIALS:
         return{
          ...state,
          credentials:aciton.payload
         }

         case UserTypes.CLEAR_USER:
          return{
            ...initialState
          }

        default: 
            return state
    }
}